package com.jbp.controller;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.model.*;
import com.jbp.service.*;
import com.jbp.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 *
 *
 * @author lucheng feng
 * @email jbp@gmail.com
 * @date 2020-06-18 21:26:42
 */
@Api(tags ="APP接口--房间相关接口" )
@ApiIgnore
@RestController
@RequestMapping("/rest/room")
public class RoomController {

    private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomWheatService roomWheatService;

    @Autowired
    private RoomUserWheatService roomUserWheatService;

    @Autowired
    private RoomBlockService roomBlockService;

    @Autowired
    private RoomCollectService roomCollectService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoomManagerService roomManagerService;

    @Autowired
    private RoomReportService roomReportService;

    @Autowired
    private TecentMsgService tecentMsgService;

    @Autowired
    private EquipRoomService equipRoomService;

    @Autowired
    private EquipService equipService;

    @Autowired
    private RoomTagService roomTagService;

    @Autowired
    private AgoraService agoraService;

    @Autowired
    private KeywordService keywordService;
    /**
     * 列表
     */
    @ApiOperation(value="根据类型查询所有房间",notes="根据类型查询所有房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="typeId",value = "房间类型 0 推荐 -1 收藏",paramType = "query"),
            @ApiImplicitParam(name="name",value = "房间名称 或 房间号",paramType = "query"),
    })
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params,@RequestAttribute("userId") Integer userId){
        params.put("userId",userId);
        PageUtils page = roomService.queryPage(params);

        return R.ok().put("data", page);
    }

    @GetMapping("/recommendRooms")
    public R recommendRooms(@RequestAttribute("userId") Integer userId){
        return R.ok().put("data", roomService.recommendRooms(userId));
    }

    /**
     * 昨日流水榜前3
     */
    @ApiOperation(value="根据类型查询所有房间",notes="根据类型查询所有房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @GetMapping("/financeRankYesterday")
    public R financeRankYesterday(){
        List<Room> rooms = roomService.financeRankYesterday();

        return R.ok().put("data", rooms);
    }


    /**
     * 房间信息
     */
    @ApiOperation(value="根据房间编号查询房间信息",notes="根据房间编号查询房间信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 不是房间uuid",paramType = "query"),

    })
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id,@RequestAttribute("userId") Integer userId){
        //用来验证房间人是否下线
        Room room = roomService.getById(id);
        //是否收藏房间
        RoomCollect collect= roomCollectService.getOne(new QueryWrapper<RoomCollect>()
                .eq("user_id",userId).eq("room_id",room.getId()));
        //在收藏房间设置collect为yes
        if (collect != null){
            room.setIsCollect("yes");
        }

        List<RoomWheat> wheats=roomWheatService.list(new QueryWrapper<RoomWheat>().eq("room_id",room.getId()));
        wheats.forEach(roomWheat -> {
            roomWheat.setOnRoomTime(new Date());
        });

        room.setWheats(wheats);
        //只返回麦上的用户
        List<RoomUserWheat>  userWheats=roomUserWheatService.list(new QueryWrapper<RoomUserWheat>().eq("room_id",room.getId()).ne("room_wheat",-1));
        boolean hasHost = false;//是否有房主
        for (RoomUserWheat roomUserWheat : userWheats) {
            User user = userService.getById(roomUserWheat.getUserId());
            roomUserWheat.setUserName(user.getName());
            roomUserWheat.setUserImg(user.getImg());
            if (Integer.valueOf(0).equals(roomUserWheat.getRoomWheat())) {
                roomUserWheat.setStatus("online");
                hasHost = true;
            }
        }
        User host = userService.getById(room.getUserId());
        room.setImg(host.getImg());
        if (!hasHost) {
            //没有房主，加房主
            RoomUserWheat hostWheat = new RoomUserWheat();
            hostWheat.setRoomWheat(0);
            hostWheat.setUserId(host.getId());
            hostWheat.setUserName(host.getName());
            hostWheat.setUserImg(host.getImg());
            hostWheat.setStatus("offline");
            userWheats.add(0, hostWheat);
        }
        room.setMood(room.getMood()+room.getFixationMood()+room.getPeopleMood());
        room.setUserWheats(userWheats);

        room.setBackground(equipRoomService.getRoomBg(room.getId()));

        return R.ok().put("data", room);
    }

    /**
     * 房间
     */
    @ApiOperation(value="房间",notes="房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="name",value = "房间名称",paramType = "query"),
    })
    @PostMapping("/save")
    public synchronized R save(@RequestBody Room room,@RequestAttribute("userId") Integer userId){
        if (StringUtils.isEmpty(room.getName())){
            return R.error("房间名称不能为空");
        }
        Room rom=roomService.getOne(new QueryWrapper<Room>().eq("user_id",userId));
        if (rom != null){
            return R.error("您已拥有房间");
        }
        keywordService.checkContent(room.getName());
        /**
         * 退出原房间
         */
        RoomUserWheat userWheat=  roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("user_id",userId));
        if (userWheat !=null){
            roomUserWheatService.removeById(userWheat.getId());
        }
        //只能个人房
        rom=new Room();
        rom.setName(room.getName());
        rom.setTypeId(7);
        String uuid= CreateUUid.createRoomCode();
        while (true) { //确保uuid唯一
            if(!isUuidExits(uuid)) {
                rom.setUuid(uuid);
                break;
            } else {
                uuid = CreateUUid.createRoomCode();
            }
        }
        rom.setUserId(userId);
        rom.setTypeName("个人");
        rom.setMood(0);
        rom.setCreateTime(new Date());
        rom.setRoomImg(room.getRoomImg());
        User user = userService.getById(userId);
        roomService.save(rom);
        /**
         * 麦位信息
         */
        for (int i = 0; i <9 ; i++) {
            RoomWheat wheat=new RoomWheat();
            wheat.setPlace(i);
            wheat.setRoomId(rom.getId());
            if (i == 0){
                wheat.setOnRoomTime(new Date());
                userWheat=new RoomUserWheat();
                userWheat.setCreateTime(new Date());
                userWheat.setUserId(userId);
                userWheat.setRoomId(rom.getId());
                userWheat.setRoomWheat(0);
                userWheat.setType("house");
                userWheat.setStatus("online");
                roomUserWheatService.save(userWheat);
            }
            wheat.setCreateTime(new Date());
            roomWheatService.save(wheat);
        }
        return R.ok(rom);
    }
    public boolean isUuidExits(String uuid) {
        QueryWrapper<Room> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uuid",uuid);
        return roomService.getOne(queryWrapper) != null;
    }


    @ApiOperation(value="我在的房间",notes="我当前在哪个房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
    })
    @GetMapping("/myRoom")
    public R myRoom(@RequestAttribute("userId") Integer userId){
        RoomUserWheat userWheat=  roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("user_id",userId));
        if (userWheat ==null){
          return R.ok().put("data",null);
        }
        Room room=roomService.getById(userWheat.getRoomId());
        User user = userService.getById(userId);
        room.setImg(user.getImg());
        return R.ok().put("data",room);
    };

    @ApiOperation(value="我的房间,以及我管理的房间",notes="我的房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
    })
    @GetMapping("/ownRoom")
    public R ownRoom(@RequestAttribute("userId") Integer userId){
        ArrayList<Integer> hostIds = new ArrayList<>();
        hostIds.add(userId);

        List<RoomManager> list = roomManagerService.list(new QueryWrapper<RoomManager>()
                .eq("user_id", userId));
        if (list!=null) {
            for (RoomManager roomManager : list) {
                hostIds.add(roomService.getById(roomManager.getRoomId()).getUserId());
            }
        }

        QueryWrapper<Room> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", hostIds);
        List<Room> rooms=roomService.list(wrapper);
        if (rooms != null) {
            for (Room room : rooms) {
                User host = userService.getById(room.getUserId());
                room.setImg(host.getImg());
                room.setMood(room.getMood()+room.getFixationMood()+room.getPeopleMood());
                room.setRole(userId.equals(room.getUserId()) ? "master" : "manager");

                if (room.getTagId()!=null) {
                    RoomTag roomTag = roomTagService.getById(room.getTagId());
                    if (roomTag!=null) {
                        room.setTagImage(roomTag.getImage());
                    }
                }
            }
        }
      return R.ok().put("data", rooms);
    }


    @ApiOperation(value="退出房间",notes="退出房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
    })
    @PostMapping("/quitRoom")
    public R quitRoom(@RequestAttribute("userId") Integer userId){
        RoomUserWheat userWheat = roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("user_id",userId));
        if (userWheat == null) {
            return R.ok();
        }

        //退出房间减50人气值
        Room room = roomService.getById(userWheat.getRoomId());
        if (room.getPeopleMood()>50) {
            room.setPeopleMood(room.getPeopleMood() - userService.getPeopleMood(userId));
            roomService.updateById(room);
        }

        roomUserWheatService.removeById(userWheat.getId());

        //修改在线状态
        User user = userService.getById(userId);
        user.setIsOnline("online");
        userService.updateById(user);

        return R.ok();
    };


    @ApiOperation(value="进入房间",notes="进入房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 这里不是房间uuid",paramType = "query"),
            @ApiImplicitParam(name="password",value = "房间密码",paramType = "query"),
    })
    @PostMapping("/inRoom")
    public synchronized R inRoom(@RequestBody Room room,@RequestAttribute("userId") Integer userId){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数为空");
        }
        room.setUserId(userId);
        roomService.inRoom(room);
        return R.ok();
    }

    @ApiOperation(value="收藏房间",notes="收藏房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 这里不是房间uuid",paramType = "query"),
    })
    @PostMapping("/collect")
    public  R collect(@RequestBody Room room,@RequestAttribute("userId") Integer userId){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数为空");
        }
        RoomCollect collect=roomCollectService.getOne(new QueryWrapper<RoomCollect>().eq("user_id",userId).eq("room_id",room.getId()));
        if (collect != null){
            return R.error("您已收藏");
        }
        collect=new RoomCollect();
        collect.setRoomId(room.getId());
        collect.setCreateTime(new Date());
        collect.setUserId(userId);
        roomCollectService.save(collect);
        return R.ok();
    }

    @ApiOperation(value="取消收藏房间",notes="取消收藏房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 这里不是房间uuid",paramType = "query"),
    })
    @PostMapping("/cancelCollect")
    public  R cancelCollect(@RequestBody Room room,@RequestAttribute("userId") Integer userId){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数为空");
        }
        RoomCollect collect=roomCollectService.getOne(new QueryWrapper<RoomCollect>().eq("user_id",userId).eq("room_id",room.getId()));
        if (collect != null){
           roomCollectService.removeById(collect.getId());
        }
        return R.ok();
    }


    @ApiOperation(value="加入 禁入 禁言",notes="加入禁入 禁言")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 这里不是房间uuid",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "进入人用户编号 不是uuid",paramType = "query"),
            @ApiImplicitParam(name = "type",value = "bear禁入mute禁言",paramType = "query")
    })
    @PostMapping("/joinBlock")
    public  R joinBlock(@RequestBody Room room,@RequestAttribute("userId") Integer userId){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数房间为空");
        }
        if (room.getUserId() == null || room.getUserId() == 0){
            return R.error("参数房间用户为空");
        }
        if (StringUtils.isEmpty(room.getType())){
            return R.error("参数房间类型为空");
        }
        Room room2 = roomService.getById(room.getId());
        RoomManager roomManager = roomManagerService.getOne(new QueryWrapper<RoomManager>()
                .eq("room_id", room.getId())
                .eq("user_id", userId)
        );
        if (userId.equals(room2.getUserId()) || roomManager!=null) {
            RoomBlock block = roomBlockService.getOne(new QueryWrapper<RoomBlock>().eq("user_id", room.getUserId()).eq("room_id", room.getId()));
            if (block == null) {
                block = new RoomBlock();
                block.setCreateTime(new Date());
                block.setRoomId(room.getId());
                block.setUserId(room.getUserId());
                block.setType(room.getType());
                roomBlockService.save(block);
            } else if (!block.getType().equals(room.getType())) {
                block.setType("all");
                roomBlockService.updateById(block);
            }
        }
        return R.ok();
    }

    @ApiOperation(value="取消禁入 禁言",notes="取消禁入 禁言")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 这里不是房间uuid",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "进入人用户编号 不是uuid",paramType = "query"),
            @ApiImplicitParam(name = "type",value = "bear禁入mute禁言",paramType = "query")
    })
    @PostMapping("/cancelBlock")
    public  R cancelBlock(@RequestBody Room room,@RequestAttribute("userId") Integer userId){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数为空");
        }
        if (room.getUserId() == null || room.getUserId() == 0){
            return R.error("参数为空");
        }
        if (StringUtils.isEmpty(room.getType())){
            return R.error("参数为空");
        }
        RoomBlock block= roomBlockService.getOne(new QueryWrapper<RoomBlock>().eq("user_id",room.getUserId()).eq("room_id",room.getId()));
        if (block != null){
            if (block.getType().equals("all")){
                if (room.getType().equals("bear")){
                    block.setType("mute");
                }else{
                    block.setType("bear");
                }
                roomBlockService.updateById(block);
            }else if(room.getType().equals(block.getType())){
                roomBlockService.removeById(block.getId());
            }

        }
        return R.ok();
    }


    @ApiOperation(value="禁入 禁言列表",notes="禁入 禁言列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = User.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 这里不是房间uuid",paramType = "query"),
            @ApiImplicitParam(name = "type",value = "bear禁入mute禁言",paramType = "query"),
    })
    @PostMapping("/blockList")
    public  R blockList(@RequestBody Room room){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数为空");
        }
//        if (room.getPage() == null){
//            return R.error("参数为空");
//        }
        if (StringUtils.isEmpty(room.getType())){
            return R.error("参数为空");
        }
        List<Integer> list=roomBlockService.getIds(room.getId(),room.getType());
        if (list == null || list.size() < 1){
            return R.ok().put("data",new ArrayList<User>());
        }
        List<User> lis=userService.list(new QueryWrapper<User>().in("id",list));
        return R.ok().put("data",lis);
//        PageUtils pageUtils=userService.queryPage(list,room.getPage());
//        return R.ok().put("data",pageUtils);
    }



    @ApiOperation(value="禁麦 、封麦",notes="禁麦 、封麦")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "麦位编号  不是 0 1 2 3 4 5 6",paramType = "query"),
            @ApiImplicitParam(name="type",value = "禁 bear 封 seal",paramType = "query"),
    })
    @PostMapping("/joinWheat")
    public  R joinWheat(@RequestBody RoomWheat roomWheat, @RequestAttribute("userId") Integer userId){
        if (roomWheat.getId() == null || roomWheat.getId() == 0){
            return R.error("参数为空");
        }
        if (StringUtils.isEmpty(roomWheat.getType())){
            return R.error("参数为空");
        }
        RoomWheat wheat=roomWheatService.getById(roomWheat.getId());
        Room room = roomService.getById(wheat.getRoomId());
        RoomManager roomManager = roomManagerService.getOne(new QueryWrapper<RoomManager>()
                .eq("room_id", room.getId())
                .eq("user_id", userId)
        );
        if (userId.equals(room.getUserId()) || roomManager!=null) {
            if (wheat != null) {
                if (roomWheat.getType().equals("bear")) {
                    wheat.setMai(1);
                } else {
                    wheat.setOffMai(1);
                }
                roomWheatService.updateById(wheat);
            }
        }
        return R.ok();
    }

    @ApiOperation(value="解禁麦 、解封麦",notes="解禁麦 、解封麦")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "麦位编号  不是 0 1 2 3 4 5 6",paramType = "query"),
            @ApiImplicitParam(name="type",value = "禁 bear 封 seal",paramType = "query"),
    })
    @PostMapping("/cancelWheat")
    public  R cancelWheat(@RequestBody RoomWheat roomWheat){
        if (roomWheat.getId() == null || roomWheat.getId() == 0){
            return R.error("参数为空");
        }
        if (StringUtils.isEmpty(roomWheat.getType())){
            return R.error("参数为空");
        }
        RoomWheat wheat=roomWheatService.getById(roomWheat.getId());
        if (wheat != null){
            if (roomWheat.getType().equals("bear")){
                wheat.setMai(0);
            }else{
                wheat.setOffMai(0);
            }
            roomWheatService.updateById(wheat);
        }
        return R.ok();
    }

    @ApiOperation(value="麦位倒计时",notes="麦位倒计时")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = RoomWheat.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "麦位编号  不是 0 1 2 3 4 5 6",paramType = "query"),
            @ApiImplicitParam(name="time",value = "倒计时时长 秒（int类型）",paramType = "query"),
    })
    @PostMapping("/wheatCountDown")
    public  R wheatCountDown(@RequestBody RoomWheat roomWheat){
        if (roomWheat.getId() == null || roomWheat.getId() == 0){
            return R.error("参数为空");
        }
        if (roomWheat.getTime() == null || roomWheat.getTime() < 0){
            return R.error("参数为空");
        }
        RoomWheat wheat=roomWheatService.getById(roomWheat.getId());
        if (wheat != null){
            wheat.setCreateTime(new Date());
            wheat.setTime(roomWheat.getTime());
            roomWheatService.updateById(wheat);
            return R.ok().put("data",wheat);
        }
        return R.error("麦位信息错误");
    }


    @ApiOperation(value="清空麦位心动值",notes="清空麦位心动值")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = RoomWheat.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "麦位编号  不是 0 1 2 3 4 5 6",paramType = "query"),
    })
    @PostMapping("/clearWheat")
    public  R clearWheat(@RequestBody RoomWheat roomWheat){
        if (roomWheat.getId() == null || roomWheat.getId() == 0){
            return R.error("参数为空");
        }
        RoomWheat wheat=roomWheatService.getById(roomWheat.getId());
        if (wheat != null){
            wheat.setCharm(0);
            roomWheatService.updateById(wheat);
            return R.ok().put("data",wheat);
        }
        return R.error("麦位信息错误");
    }


    @ApiOperation(value="清空所有麦位心动值",notes="清空所有麦位心动值")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = RoomWheat.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
    })
    @PostMapping("/clearAllWheat")
    public  R clearAllWheat(@RequestBody RoomWheat roomWheat){
        if (roomWheat.getRoomId() == null || roomWheat.getRoomId() == 0){
            return R.error("参数为空");
        }
        List<RoomWheat> list=roomWheatService.list(new QueryWrapper<RoomWheat>().eq("room_id",roomWheat.getRoomId()));
        if (list != null && list.size() > 0){
            list.forEach(li -> {
                li.setCharm(0);
                roomWheatService.updateById(li);
            });
            return R.ok().put("data",list);
        }
        return R.error("房间信息错误");
    }


    @ApiOperation(value="设置主持人",notes="设置主持人")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "主持人用户编号",paramType = "query"),
    })
    @PostMapping("/presenter")
    public  R presenter(@RequestBody RoomUserWheat roomUserWheat){
        if (roomUserWheat.getRoomId() == null || roomUserWheat.getRoomId() == 0){
            return R.error("参数为空");
        }
        if (roomUserWheat.getUserId() == null || roomUserWheat.getUserId() == 0){
            return R.error("参数为空");
        }
        roomUserWheatService.presenter(roomUserWheat);
        return R.ok();
    }


    /**
     * 设置管理员
     */
    @ApiOperation(value="设置管理员",notes="设置管理员")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="uuid",value = "uuid",paramType = "query"),
    })
    @PostMapping("/addMananger")
    public  R addMananger(@RequestBody RoomManager roomManager){
        if (roomManager.getRoomId() == null || roomManager.getRoomId() == 0){
            return R.error("参数为空");
        }
        if (StringUtils.isEmpty(roomManager.getUuid())){
            return R.error("参数为空");
        }
        User us=  userService.getOne(new QueryWrapper<User>().eq("uuid",roomManager.getUuid()));
        if (us == null){
            return R.error("账号不存在");
        }
        RoomManager manager=roomManagerService.getOne(new QueryWrapper<RoomManager>().eq("user_id",us.getId()).eq("room_id",roomManager.getRoomId()));
        if (manager == null){
            roomManager.setUserId(us.getId());
            roomManager.setCreateTime(new Date());
            roomManagerService.save(roomManager);
        }
        return R.ok();
    }
    /**
     * 删除管理员
     */
    @ApiOperation(value="删除管理员",notes="删除管理员")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "用户编号",paramType = "query"),
    })
    @PostMapping("/delMananger")
    public  R delMananger(@RequestBody RoomManager roomManager){
        if (roomManager.getRoomId() == null || roomManager.getRoomId() == 0){
            return R.error("参数为空");
        }
        if (roomManager.getUserId() == null || roomManager.getUserId() == 0){
            return R.error("参数为空");
        }
        RoomManager manager=roomManagerService.getOne(new QueryWrapper<RoomManager>().eq("user_id",roomManager.getUserId()).eq("room_id",roomManager.getRoomId()));
        if (manager != null){
            roomManagerService.removeById(manager.getId());
        }
        return R.ok();
    }

    /**
     * 管理员列表
     */
    @ApiOperation(value="管理员列表",notes="管理员列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = User.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
//            @ApiImplicitParam(name="page",value = "当前页",paramType = "query"),
    })
    @PostMapping("/manangerList")
    public  R manangerList(@RequestBody RoomManager roomManager){
        if (roomManager.getRoomId() == null || roomManager.getRoomId() == 0){
            return R.error("参数为空");
        }
//        if (roomManager.getPage() == null){
//            return R.error("参数为空");
//        }
        List<Integer> list=roomManagerService.getUserIds(roomManager.getRoomId());
        if (list == null || list.size() < 1){
            return R.ok().put("data",new ArrayList<User>());
        }
        List<User> lis=userService.list(new QueryWrapper<User>().in("id",list));
        return R.ok().put("data",lis);
//        PageUtils pageUtils=userService.queryPage(list,roomManager.getPage());
//        return R.ok().put("data",pageUtils);
    }

    /**
     * 修改房间信息
     */
    @ApiOperation(value="修改房间信息",notes="修改房间信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Room.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="welcome",value = "欢迎语",paramType = "query"),
            @ApiImplicitParam(name="play",value = "玩法",paramType = "query"),
            @ApiImplicitParam(name="onCharm",value = "心动值开关 0 关闭 1 开启",paramType = "query"),
            @ApiImplicitParam(name="isGift",value = "礼物特效 0 关闭 1 开启",paramType = "query"),
            @ApiImplicitParam(name="screen",value = "公屏 0 关闭 1 开启",paramType = "query"),
            @ApiImplicitParam(name="name",value = "房间名",paramType = "query"),
            @ApiImplicitParam(name="encryption",value = "是否加密 0 不加密 1 加密",paramType = "query"),
            @ApiImplicitParam(name="password",value = "password",paramType = "query"),
            @ApiImplicitParam(name="luckMsg",value = "抽奖公屏消息",paramType = "query"),
    })
    @PostMapping("/updateRoom")
    public R updateRoom(@RequestBody Room room){
        if (room.getId() == null || room.getId() == 0){
            return R.error("参数为空");
        }
        Room rom=roomService.getById(room.getId());
        if (rom == null){
            return R.error("房间信息错误");
        }
        if (!StringUtils.isEmpty(room.getWelcome())){
            keywordService.checkContent(room.getWelcome());
            rom.setWelcome(room.getWelcome());
        }
        if (!StringUtils.isEmpty(room.getPlay())){
            keywordService.checkContent(room.getPlay());
            rom.setPlay(room.getPlay());
        }
        if (room.getOnCharm() != null){
            rom.setOnCharm(room.getOnCharm());
        }
        if (room.getIsGift() != null){
            rom.setIsGift(room.getIsGift());
        }
        if (room.getScreen() != null){
            rom.setScreen(room.getScreen());
        }
        if (room.getLuckMsg() != null){
            rom.setLuckMsg(room.getLuckMsg());
        }
        if (!StringUtils.isEmpty(room.getName())){
            keywordService.checkContent(room.getName());
            rom.setName(room.getName());
        }
        if (room.getEncryption() != null && room.getEncryption().equals(1)){
           if (StringUtils.isEmpty(room.getPassword())){
               return R.error("密码为空");
           }
            rom.setEncryption(1);
            rom.setPassword(room.getPassword());
        }else{
            rom.setEncryption(0);
            rom.setPassword("");
        }
        if (!StringUtils.isEmpty(room.getRoomImg())){
            rom.setRoomImg(room.getRoomImg());
        }
        roomService.updateById(rom);
        return R.ok().put("data",rom);
    }



    /**
     * 在线房间列表
     */
    @ApiOperation(value="在线房间用户列表",notes="在线房间用户列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = User.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
//            @ApiImplicitParam(name="page",value = "当前页",paramType = "query"),
    })
    @PostMapping("/roomUserList")
    public  R roomUserList(@RequestBody RoomManager roomManager){
        if (roomManager.getRoomId() == null || roomManager.getRoomId() == 0){
            return R.error("参数为空");
        }
//        if (roomManager.getPage() == null){
//            return R.error("参数为空");
//        }
        List<Integer> list=roomUserWheatService.getUserIds(roomManager.getRoomId());
        if (list == null || list.size() < 1){
            return R.ok().put("data",new ArrayList<User>());
        }
        List<User> lis=userService.list(new QueryWrapper<User>().in("id",list));
        return R.ok().put("data",lis);
//        PageUtils pageUtils=userService.queryPage(list,roomManager.getPage());
//        return R.ok().put("data",pageUtils);
    }

    /**
     * 举报房间
     */
    @ApiOperation(value="举报房间",notes="举报房间")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="body",value = "举报内容",paramType = "query"),
            @ApiImplicitParam(name="img",value = "图片",paramType = "query"),
    })
    @PostMapping("/roomReport")
    public R roomReport(@RequestBody RoomReport roomReport,@RequestAttribute("userId") Integer userId){
        if (roomReport.getRoomId() == null || roomReport.getRoomId() == 0){
            return R.error("参数为空");
        }
        if (StringUtils.isEmpty(roomReport.getImg())){
            return R.error("参数为空");
        }
        roomReport.setUserId(userId);
        roomReport.setCreateTime(new Date());
        roomReportService.save(roomReport);
        return R.ok();
    }


    @ApiOperation(value="上麦",notes="上麦")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="roomWheat",value = "麦位号 0 1 2 3 4 5 6 7 8 9 ",paramType = "query"),
    })
    @PostMapping("/upWheat")
    public synchronized  R upWheat(@RequestBody RoomUserWheat roomUserWheat,@RequestAttribute("userId") Integer userId){
        if (roomUserWheat.getRoomId() == null || roomUserWheat.getRoomId() == 0){
            return R.error("参数为空");
        }
        if (roomUserWheat.getRoomWheat() == null || roomUserWheat.getRoomWheat() < 0){
            return R.error("参数为空");
        }
        /**检查麦位是否已封*/
        RoomWheat roomWheat = roomWheatService.getOne(new QueryWrapper<RoomWheat>().eq("room_id", roomUserWheat.getRoomId()).eq("place", roomUserWheat.getRoomWheat()));
        if (roomWheat.getOffMai()==1) {
            return R.error("麦位已被封");
        }
        /**
         *
         * 查看麦位是否为空
         */
        RoomUserWheat wheat=roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("room_id",roomUserWheat.getRoomId()).eq("room_wheat",roomUserWheat.getRoomWheat()));
        if (wheat != null){
            return R.error("麦位已被占");
        }

        wheat=roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("user_id",userId).eq("room_id",roomUserWheat.getRoomId()));
        if (wheat == null){
            return R.error("房间错误");
        }
        wheat.setRoomWheat(roomUserWheat.getRoomWheat());
        roomUserWheatService.updateById(wheat);

        Map<String, String> map = new HashMap<>();
        map.put("token", agoraService.getRtctoken(roomUserWheat.getRoomId().toString(), userId, true));
        return R.ok(map);
    }

    @ApiOperation(value="下麦",notes="下麦")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
    })
    @PostMapping("/downWheat")
    public  R presenter(@RequestBody RoomUserWheat roomUserWheat,@RequestAttribute("userId") Integer userId){
        ///可以下自己，也可以下别人
        RoomUserWheat   wheat=roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("user_id",roomUserWheat.getUserId()).eq("room_id",roomUserWheat.getRoomId()));
        if (wheat != null){
            wheat.setRoomWheat(-1);
            roomUserWheatService.updateById(wheat);
        }
        return R.ok();
    }

    @ApiOperation(value="验证进入房间是否要密码",notes="验证进入房间是否要密码")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功 1 需要密码登录  0 不需要"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
    })
    @GetMapping("/isPassword/{roomId}")
    public R getIsPassword(@PathVariable("roomId") Integer roomId,@RequestAttribute("userId") Integer userId){
        //验证是否管理员
       RoomManager roomManager =   roomManagerService.getOne(new QueryWrapper<RoomManager>().eq("user_id",userId).eq("room_id",roomId));
       if (roomManager != null){
           return R.ok().put("data","0");
       }
       //验证是否房主
       Room room=  roomService.getOne(new QueryWrapper<Room>().eq("id",roomId).eq("user_id",userId));
       if (room != null){
           return R.ok().put("data","0");
       }
       //是否已在这个房间
       RoomUserWheat wheat= roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>().eq("room_id",roomId).eq("user_id",userId));
       if (wheat != null){
           return R.ok().put("data","0");
       }
       return R.ok().put("data","1");
    }


    @ApiOperation(value="麦拉心动值开关设置",notes="麦拉心动值开关设置")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功 1开启成功 0关闭成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="id",value = "房间编号 不是 房间uuId",paramType = "query"),
            @ApiImplicitParam(name="onCharm",value = "0 关闭 1打开",paramType = "query"),
    })
    @PostMapping("/isRoomWheat")
    public R isRoomWheat(@RequestBody Room room){
        if (room == null){
            return R.error("无效参数");
        }
        if (room.getId() == null || room.getOnCharm() == null || (room.getOnCharm() < 0 && room.getOnCharm() > 1)){
            return R.error("参数格式错误");
        }
        Room rm = roomService.getById(room.getId());
        if (rm == null){
            return R.error("房间错误");
        }
        //设置心动值开关
        rm.setOnCharm(room.getOnCharm());
        roomService.updateById(rm);
        if (room.getOnCharm() == 0) {//如果关闭心动值  麦拉所有心动值清0
            roomService.clearCharm(rm.getId());
        }
        return R.ok(rm.getOnCharm());
    }


    @ApiOperation(value="清空麦拉心动值",notes="清空麦拉心动值")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="roomId",value = "房间编号 不是 房间uuId",paramType = "query"),
    })
    @GetMapping("/clearCharm/{roomId}")
    public R clearCharm(@PathVariable("roomId") Integer rmId){
        roomService.clearCharm(rmId);
        return R.ok();
    }


    /** 发送全局消息 */
    @ApiOperation(value="清空麦拉心动值",notes="清空麦拉心动值")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "message",value = "消息内容",paramType = "body"),
    })
    @PostMapping("/sendGlobalMsg")
    public R sendGlobalMsg(@RequestBody Map<String, Object> params){
        String message = (String) params.get("message");
        String account = (String) params.get("account");
        Integer roomId = (Integer) params.get("roomId");
        try {
            new Thread(() -> tecentMsgService.sendOnlineBroadCast(message, roomId, account)).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*executor.submit(() -> {
            tecentMsgService.sendOnlineBroadCast(message, roomId, account);
        });*/

        return R.ok();
    }

}
